package com.sx.first.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import com.sx.first.dao.ProductDAO;
import com.sx.first.model.Product;

@Repository("productDAO")
@Scope("prototype")
public class ProductDAO {
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public List<Product> findAll() {
		@SuppressWarnings("unchecked")
		List<Product> list = sessionFactory.getCurrentSession().createQuery("from Product").list();
		return list;
	}

	public void save(Product pro) {
		sessionFactory.getCurrentSession().save(pro);
	}

	public void delete(Product pro) {
		sessionFactory.getCurrentSession().delete(pro);
	}

	public void update(Product pro) {
		sessionFactory.getCurrentSession().update(pro);
	}

	public Product findById(int proId) {
		return sessionFactory.getCurrentSession().get(Product.class, proId);
	}

	public List<Product> findAllByMatId(Integer matId) {
		@SuppressWarnings({ "unchecked" })
		List<Product> list = sessionFactory.getCurrentSession()
				.createQuery("from Product as p where p.mat.matId = :matId order by p.proId desc")
				.setParameter("matId", matId).list();
		for (Product product : list) {
			Hibernate.initialize(product.getMat());
		}
		return list;
	}

}
